<template>
  <div class="dashboard-container">
    <div class="say-hello">
      <div class="avatar-area">
        <img src="../../assets/login-logo.png" alt="我的头像">
      </div>
      <div class="hello-content">
        <div class="hello">{{ hello[index] }},{{ name }},{{ words[index] }}</div>
        <div class="title">当前学期：{{ currentTermObj.name || '暂未开学' }}</div>
        <div v-permission="[settings.teacherPerm]" class="title">{{ roleName }}</div>
      </div>
      <div v-permission="[settings.managePerm]" class="right">
        <div class="calc-item">
          <div class="calc-title">送教任务</div>
          <div class="calc-num">{{ numberObj.outworkNum || 0 }}个</div>
        </div>
        <div class="calc-item">
          <div class="calc-title">送教老师</div>
          <div class="calc-num">{{ numberObj.outworkTeacherNum || 0 }}人</div>
        </div>
        <div class="calc-item">
          <div class="calc-title">送教学生</div>
          <div class="calc-num">{{ numberObj.outworkStudentNum || 0 }}人</div>
        </div>
        <div class="calc-item">
          <div class="calc-title">在籍学生</div>
          <div class="calc-num">{{ numberObj.totalStudentNum || 0 }}人</div>
        </div>
      </div>
    </div>
    <div v-if="showStudentChart || showTaskChart" class="dashboard-title">
      送教情况
      <el-dropdown style="float: right;" @command="handleCommand">
        <span class="el-dropdown-link">
          {{ currentTermName }}<i class="el-icon-arrow-down el-icon--right" />
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-for="item in termOptions" :key="item.value" :command="item">{{ item.label }}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <el-row v-if="showStudentChart || showTaskChart" :gutter="20">
      <el-col v-if="showStudentChart" :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>学生分布</span>
            <div
              :class="{ 'tab-btn': true, active: current === 'village' }"
              @click="changeCondition('village')"
            >
              按乡镇
            </div>
            <div
              :class="{ 'tab-btn': true, active: current === 'gender' }"
              @click="changeCondition('gender')"
            >
              按性别
            </div>
            <div
              :class="{ 'tab-btn': true, active: current === 'class' }"
              @click="changeCondition('class')"
            >
              按年级
            </div>
            <div
              :class="{ 'tab-btn': true, active: current === 'type' }"
              @click="changeCondition('type')"
            >
              按残疾类型
            </div>
          </div>
          <echart
            v-show="current === 'type'"
            id="student-type"
            style="margin: 0 auto;"
            :options="typeOption"
            :width="500"
            :height="400"
          />
          <echart
            v-show="current === 'class'"
            id="student-class"
            style="margin: 0 auto;"
            :options="classOption"
            :width="500"
            :height="400"
          />
          <echart
            v-show="current === 'gender'"
            id="student-gender"
            style="margin: 0 auto;"
            :options="genderOption"
            :width="500"
            :height="400"
          />
          <echart
            v-show="current === 'village'"
            id="student-village"
            style="margin: 0 auto;"
            :options="villageOption"
            :width="500"
            :height="400"
          />
        </el-card>
      </el-col>
      <el-col v-if="showTaskChart" :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>送教任务完成情况</span>
          </div>
          <echart
            id="sj"
            style="margin: 0 auto;"
            :options="sjOption"
            :width="500"
            :height="400"
          />
          <div class="send-ratio">送教率：{{ sendRatio }}%</div>
        </el-card>
      </el-col>
    </el-row>
    <div v-if="verifyList && verifyList.length > 0" v-permission="[settings.managePerm]" class="dashboard-title">我的任务</div>
    <el-row v-if="verifyList && verifyList.length > 0" :gutter="20">
      <el-col>
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>待审核送教任务<span
              style="color: red; font-weight: 600"
            >（共{{ total }}条）</span></span>
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              @click="goToVerifyList"
            >查看全部</el-button>
          </div>
          <div v-for="item in verifyList" :key="item.outworkRecordId" class="item">
            <a class="text"> {{ item.teacherName }}老师提交的【{{ item.typeName }}】提报</a>
            <div class="sub-time">{{ item.createdTime | format('YYYY-MM-DD HH:mm:ss') }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Echart from '@/components/echart'
import { getStaticStudent, getStaticTask, getVerifyList, getStaticNum } from '@/api/task'
import { getAllTerm } from '@/api/basic'
import { getLabelByValue } from '@/utils/index'
import { recordTypeOptions } from '@/views/task/attr'
import settings from '@/settings'

export default {
  name: 'Dashboard',
  components: { Echart },
  data() {
    return {
      settings,
      hello: ['早上好', '中午好', '下午好', '晚上好', '夜深了'],
      words: [
        '祝你工作开心！',
        '该吃饭午休了！',
        '祝你工作开心！',
        '工作辛苦了！',
        '祝你好梦相伴'
      ],
      index: 0,
      // 图表
      showStudentChart: false,
      showTaskChart: false,
      current: 'type', // type 残疾类型  class 年级  gender 性别 village 乡镇
      sjOption: {},
      typeOption: {},
      classOption: {},
      genderOption: {},
      villageOption: {},
      termOptions: [],
      currentTermName: '选择学期',
      currentTermId: null,
      currentTermObj: {},
      verifyList: [],
      total: 0,
      numberObj: {},
      name: '',
      roleName: '',
      sendRatio: 0
    }
  },
  mounted() {
    const store = this.$store.getters
    this.name = store.user.realName
    if (store.roles && store.roles.length > 0) {
      this.roleName = store.roles[0] === 'role_admin' ? '管理员' : '教师'
      if (store.roles[0] === 'role_admin') {
        this.name = '管理员'
      }
    }
    this.checkTime()
    if (this.roleName === '管理员') {
      this.getVerifyTask()
    }
    this.getTermList()
  },
  methods: {
    checkTime() {
      let index = 0
      const hour = new Date().getHours()
      if (hour >= 6 && hour < 12) {
        // morning
        index = 0
      } else if (hour >= 12 && hour < 14) {
        //
        index = 1
      } else if (hour >= 14 && hour < 18) {
        // 1
        index = 2
      } else if (hour >= 18 && hour < 23) {
        index = 3
      } else {
        index = 4
      }
      this.index = index
    },
    changeCondition(type) {
      if (this.current !== type) {
        this.current = type
      }
    },
    handleCommand(term) {
      if (term.value !== this.currentTermId) {
        this.currentTermName = term.label
        this.currentTermId = term.value
        this.querySendStatic(term.value)
      }
    },
    querySendStatic(id) {
      this.getTask(id)
      this.getStudent(id)
      if (this.roleName === '管理员') {
        this.getStaticNumber(id)
      }
    },
    async getTermList() {
      try {
        const res = await getAllTerm({})
        if (res && res.length) {
          const list = res.filter(v => v.status === 1 || v.status === 2)
          this.termOptions = list.map(v => ({
            label: v.name,
            value: v.id
          }))
          if (list.length > 0) {
            const current = res.filter(v => v.status === 1)
            if (current.length > 0) {
              this.currentTermName = current[0].name
              this.currentTermId = current[0].id
              this.querySendStatic(current[0].id)
              this.currentTermObj = JSON.parse(JSON.stringify(current[0]))
            } else {
              this.currentTermName = list[0].name
              this.currentTermId = list[0].id
              this.querySendStatic(list[0].id)
            }
          }
        }
      } catch (err) {
        console.log(err)
      }
    },
    async getTask(schoolTermId) {
      try {
        const res = await getStaticTask({
          schoolTermId
        })
        if (res && res.length > 0) {
          this.showTaskChart = true
          let sendTime = 0, unsendTime = 0, total = 0;
          res.forEach(v => {
            if (v.name === '已送教次数') {
              sendTime = v.num || 0;
            } else if (v.name === '未送教次数') {
              unsendTime = v.num || 0;
            }
          })
          total = sendTime + unsendTime;
          this.sendRatio = ((sendTime / total) * 100).toFixed(2);
          this.sjOption = {
            title: {
              text: '送教完成情况统计',
              subtext: `共${total / 20}名学生,需完成送教${total}次`,
              left: 'center'
            },
            tooltip: {
              trigger: 'item'
            },
            legend: {
              orient: 'vertical',
              left: 'left'
            },
            series: [
              {
                name: '次数',
                type: 'pie',
                radius: '50%',
                data: res.map(v => ({
                  value: v.num,
                  name: v.name
                })),
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          }
        }
      } catch (err) {
        console.log(err)
      }
    },
    async getStudent(schoolTermId) {
      try {
        const res = await getStaticStudent({
          schoolTermId
        })
        if (res && JSON.stringify(res) !== '{}') {
          this.showStudentChart = true
          for (const key in res) {
            switch (key) {
              case '1':
                this.typeOption = {
                  title: {
                    text: '送教对象按残疾类型分布统计',
                    subtext: `共${res[key].length > 1 ? res[key].reduce(function(prev, curr) {
                      return (typeof prev === 'number' ? prev : prev.num) + curr.num
                    }) : (res[key].length === 1 ? res[key][0].num : 0)}人`,
                    left: 'center'
                  },
                  tooltip: {
                    trigger: 'item'
                  },
                  legend: {
                    orient: 'vertical',
                    left: 'left'
                  },
                  series: [
                    {
                      name: '学生人数',
                      type: 'pie',
                      radius: '50%',
                      data: res[key].map(v => ({
                        value: v.num,
                        name: v.name
                      })),
                      emphasis: {
                        itemStyle: {
                          shadowBlur: 10,
                          shadowOffsetX: 0,
                          shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                      }
                    }
                  ]
                }
                break
              case '2':
                this.classOption = {
                  title: {
                    text: '送教对象按年级分布统计',
                    subtext: `共${res[key].length > 1 ? res[key].reduce(function(prev, curr) {
                      return (typeof prev === 'number' ? prev : prev.num) + curr.num
                    }) : (res[key].length === 1 ? res[key][0].num : 0)}人`,
                    left: 'center'
                  },
                  tooltip: {
                    trigger: 'item'
                  },
                  legend: {
                    orient: 'vertical',
                    left: 'left'
                  },
                  series: [
                    {
                      name: '学生人数',
                      type: 'pie',
                      radius: ['40%', '70%'],
                      avoidLabelOverlap: false,
                      label: {
                        show: false,
                        position: 'center'
                      },
                      data: res[key].map(v => ({
                        value: v.num,
                        name: v.name
                      })),
                      emphasis: {
                        itemStyle: {
                          shadowBlur: 10,
                          shadowOffsetX: 0,
                          shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                      },
                      labelLine: {
                        show: false
                      }
                    }
                  ]
                }
                break
              case '3':
                this.genderOption = {
                  title: {
                    text: '送教对象按性别分布统计',
                    subtext: `共${res[key].length > 1 ? res[key].reduce(function(prev, curr) {
                      return (typeof prev === 'number' ? prev : prev.num) + curr.num
                    }) : (res[key].length === 1 ? res[key][0].num : 0)}人`,
                    left: 'center'
                  },
                  tooltip: {
                    trigger: 'item'
                  },
                  legend: {
                    orient: 'vertical',
                    left: 'left'
                  },
                  series: [
                    {
                      name: '学生人数',
                      type: 'pie',
                      radius: ['40%', '70%'],
                      center: ['50%', '60%'],
                      roseType: 'area',
                      itemStyle: {
                        borderRadius: 3
                      },
                      data: res[key].map(v => ({
                        value: v.num,
                        name: v.name
                      }))
                    }
                  ]
                }
                break
              case '4':
                this.villageOption = {
                  title: {
                    text: '送教对象乡镇分布统计',
                    subtext: `共${res[key].length > 1 ? res[key].reduce(function(prev, curr) {
                      return (typeof prev === 'number' ? prev : prev.num) + curr.num
                    }) : (res[key].length === 1 ? res[key][0].num : 0)}人`,
                    left: 'center'
                  },
                  tooltip: {
                    trigger: 'item'
                  },
                  legend: {
                    orient: 'vertical',
                    left: 'left'
                  },
                  series: [
                    {
                      name: '学生人数',
                      type: 'pie',
                      radius: ['40%', '70%'],
                      center: ['50%', '60%'],
                      roseType: 'area',
                      itemStyle: {
                        borderRadius: 5
                      },
                      data: res[key].map(v => ({
                        value: v.num,
                        name: v.name
                      }))
                    }
                  ]
                }
                break
              default:
            }
          }
        } else {
          this.showStudentChart = false
        }
        console.log(res)
      } catch (err) {
        console.log(err)
      }
    },
    async getStaticNumber(schoolTermId) {
      try {
        const res = await getStaticNum({
          schoolTermId
        })
        if (res) {
          this.numberObj = res
        }
      } catch (err) {
        console.log(err)
      }
    },
    async getVerifyTask() {
      try {
        const res = await getVerifyList({
          status: 0,
          pageNum: 1,
          pageSize: 5
        })
        if (res && res.list) {
          this.verifyList = res.list.map(v => ({ ...v, typeName: getLabelByValue(v.type, recordTypeOptions) }))
          this.total = res.totalElements
        }
      } catch (err) {
        console.log(err)
      }
    },
    goToVerifyList() {
      this.$router.push({
        path: '/task/verify'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  .say-hello {
    background: #fff;
    padding: 15px;
    display: table;
    width: 100%;
    .avatar-area {
      display: table-cell;
      width: 72px;
      height: 72px;
      img {
        width: 72px;
        height: 72px;
        border-radius: 36px;
      }
    }
    .hello-content {
      display: table-cell;
      vertical-align: middle;
      padding-left: 20px;
      .hello {
        padding-bottom: 5px;
        font-size: 20px;
        font-weight: 500;
      }
      .title {
        color: rgba(0, 0, 0, 0.45);
        font-size: 14px;
        padding-bottom: 5px;
      }
    }
    .right {
      display: table-cell;
      vertical-align: middle;
      overflow: hidden;
      width: 500px;
      .calc-item {
        float: right;
        padding: 0 32px;
        text-align: right;
        position: relative;
        .calc-title {
          margin-bottom: 10px;
          color: rgba(0, 0, 0, 0.45);
          font-size: 14px;
        }
        .calc-num {
          color: rgba(0, 0, 0, 0.85);
          font-size: 20px;
        }
        &:after {
          content: "";
          display: block;
          width: 1px;
          height: 40px;
          position: absolute;
          top: 8px;
          right: 0;
          background: #f0f0f0;
        }
        &:first-child {
          padding-right: 0;
          &:after {
            background: none;
          }
        }
      }
    }
  }
  .box-card {
    margin-top: 10px;
    position: relative;
    .send-ratio {
      position: absolute;
      bottom: 20px;
      left: 20px;
    }
    .clearfix {
      .tab-btn {
        float: right;
        padding: 3px 0;
        margin-left: 10px;
        font-size: 14px;
        cursor: pointer;
        &.active {
          color: #409eff;
        }
      }
    }
    .item {
      overflow: hidden;
      font-size: 14px;
      line-height: 30px;
      .text {
        float: left;
        display: block;
        border: none;
        &:hover {
          text-decoration: underline;
          color: #409eff;
        }
      }
      .sub-time {
        float: right;
        color: rgba(0, 0, 0, 0.45);
      }
    }
  }
  .dashboard-title {
    background: #fff;
    margin-top: 10px;
    padding: 20px;
    font-size: 20px;
    font-weight: 600;
  }
}
</style>
